<!--
*@Author: zt
*@Description: 添加备勤人员
*@Date: 2024-08-21
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :confirmLoading="loading"
    @submit="submit"
    @close="dialogClose"
    :hideBtns="attrs.dbDisabled ? ['submit'] : []">
    <a-layout class="f-h-100 s-bg-white">
      <a-layout-content style="overflow: hidden">
        <a-row
          :gutter="60"
          class="f-h-100">
          <a-col :span="12">
            <u-busi-card title="基本信息">
              <u-form
                :elements="formEls"
                :model="form"
                :loading="loading"
                :gutter="0"
                ref="formRef"></u-form>
            </u-busi-card>

            <u-busi-card title="成员信息">
              <a-list
                :grid="{ gutter: [16, 16], column: 4 }"
                style="margin-left: 8px"
                :data-source="userList">
                <template #renderItem="{ item }">
                  <a-row align="middle">
                    <div class="u-name-box">{{ item.label }}</div>
                    <a-space
                      direction="vertical"
                      align="middle"
                      class="f-margin-l10">
                      <span class="u-span-name f-font-family">
                        {{ item.label }}
                      </span>
                      <span class="u-span-value f-font-family">
                        当月备勤天数
                        <span style="color: #333">
                          {{ item.standsDays }}
                        </span>
                      </span>
                    </a-space>
                  </a-row>
                </template>
              </a-list>
            </u-busi-card>
          </a-col>
          <a-col
            :span="12"
            class="f-h-100">
            <div class="f-flex-column f-h-100">
              <Calendar
                :showExtraTool="false"
                v-model:date="clickDateValue"
                :data="calendarData"
                @search="getCalendarData"
                @item-click="
                  (data) => {
                    userListRow(data.standbyDate);
                  }
                "></Calendar>
            </div>
          </a-col>
        </a-row>
      </a-layout-content>
    </a-layout>

    <u-sel-user v-model:open="showSelUser"></u-sel-user>
    <userRow
      v-model:open="showUserRow"
      width="80%"
      :data="useListData"
      title="当日备勤人员" />
  </u-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, useAttrs } from "vue";
import { useBaseStore } from "@/store";
import { storeToRefs } from "pinia";
import { alertC, messageC, isValue } from "@/util/common";
import { cloneDeep } from "lodash";
import dayjs, { Dayjs } from "dayjs";
import Calendar from "@/views/oa/assist/myCalender/Calender.vue";
import userRow from "./row.vue";
import * as userService from "@/service/system/user/index";
import * as beDutyApi from "@/service/administration/beDuty/index";

const props = defineProps<{
  calenderValue?: string;
}>();
const attrs = useAttrs();

const emits = defineEmits(["success", "close"]);

const { deptData, deptUsers } = storeToRefs(useBaseStore());

let showUserRow = ref(false);
let useListData = ref([]);
const formRef = ref<FormInstance>();
const form = reactive<any>({
  fkdeptname: "",
  standbyDate: dayjs(new Date()).format("YYYY-MM-DD"),
  backuptype: 1,
});
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: "90px",
  colon: false,
};

let userList = ref([]);

// 当前选中部门的人员
const currentDeptUsers = computed(() => {
  let dept = deptUsers.value.find((i) => i.keyid == form.fkdeptid);
  return dept ? dept["children"] || [] : [];
});

let showSelUser = ref<boolean>(false);
const formEls: Array<_IFormEl> = reactive([
  {
    label: "备勤时间",
    key: "standbyDate",
    col: { span: 24 },
    element: "datepicker",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      allowClear: false,
      onChange: function (val) {
        clickDateValue.value = dayjs(val).format("YYYY-MM-DD");
        getCalendarData();
        showUserList();
      },
    },
  },
  {
    label: "备勤部门",
    key: "fkdeptid",
    col: { span: 24 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: deptData.value,
      fieldNames: { label: "name", value: "keyid" },
      onChange: (val, option) => {
        form.fkdeptname = option ? option.name : "";
        form.fkuserids = "";
      },
    },
  },
  {
    label: "备勤人员",
    key: "fkuserids",
    col: { span: 24 },
    element: "select",
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      options: currentDeptUsers,
      fieldNames: { label: "name", value: "keyid" },
      mode: "multiple",
    },
  },
  {
    label: "备注",
    key: "reason",
    col: { span: 24 },
    element: "textarea",
    formItemProps: { ...formItemProps },
  },
  {
    label: "附件",
    key: "appendixSaveVOList",
    col: { span: 24 },
    element: "file",
    formItemProps: { ...formItemProps },
    componentProps: {
      fileParams: { biztype: "5", bucket: "ADM" },
    },
  },
]);

// 保存提交
const loading = ref<boolean>(false);
const submit = async () => {
  loading.value = true;
  try {
    await formRef.value.form.validate();

    form["backuptype"] = 1;
    let tFrom = cloneDeep(form);

    tFrom.backuptype = 1;
    const result = await beDutyApi.add(tFrom);
    if (result.code == 0) {
      emits("success", form.standbyDate);
      messageC(result.msg, "success");
      form.fkdeptid = "";
      form.fkuserids = "";
      form.standbyDate = "";
      form.reason = "";
      delete form["appendixSaveVOList"];
    } else {
      alertC(result.msg, "warning");
    }
  } catch (error) {}

  loading.value = false;
};

// 日历数据
const clickDateValue = ref<Dayjs>(dayjs().format("YYYY-MM-DD"));
const calendarData = ref<any[]>([]);
const nowCalenarData = ref<object>({});
const getCalendarData = async () => {
  try {
    const res = await beDutyApi.dutyUserPage({
      datetime: clickDateValue.value,
      backuptype: 1,
    });
    if (res.code == 0) {
      let count = {};
      let tData = res.data || [];
      tData.forEach((item) => {
        count[item.standbyDate] = (count[item.standbyDate] || 0) + 1;
        if (count[item.standbyDate] < 4) {
          (item.scheduledate = dayjs(item.standbyDate).format("YYYY-MM-DD HH:mm:ss")), (item.theme = item.fkusername);
        } else if (count[item.standbyDate] == 4) {
          (item.scheduledate = dayjs(item.standbyDate).format("YYYY-MM-DD HH:mm:ss")), (item.theme = "...");
        } else {
          return;
        }
      });
      calendarData.value = tData;
      nowCalenarData.value[dayjs(clickDateValue.value).format("YYYY-MM")] = tData;
    }
  } catch (error) {}
};

// 查询视图数据
const userListRow = async (date) => {
  try {
    const res = await beDutyApi.dutyUserPage({
      datetime: clickDateValue.value,
      backuptype: 1,
    });
    if (res.code == 0) {
      let tData = res.data || [];
      tData.forEach((item) => {
        (item.scheduledate = dayjs(item.standbyDate).format("YYYY-MM-DD HH:mm:ss")), (item.theme = item.fkusername);
      });
      useListData.value = [];
      tData.forEach((item) => {
        if (item.scheduledate == date) {
          useListData.value.push(item);
        }
      });
      showUserRow.value = true;
    }
  } catch (error) {}
};

//获取回显数据
const getHX = async () => {
  loading.value = true;
  try {
    const res = await beDutyApi.getQuery(attrs.keyid);
    if (res.code == 0) {
      for (let key in res.data) {
        if (key == "appendix") {
          form["appendixSaveVOList"] = res.data[key];
        } else {
          form[key] = res.data[key];
        }
      }
      form.fkuserids = form["fkuserid"] || "";
    }
  } catch (error) {}
  loading.value = false;
};

// 展示选中人员的成员信息
const showUserList = () => {
  let monthDatas = nowCalenarData.value[dayjs(form.standbyDate).format("YYYY-MM")] || [];

  let ids = (form["fkuserids"] || "").split(",").filter((i) => isValue(i));
  userList.value = currentDeptUsers.value
    .filter((i) => ids.includes(i.keyid))
    .map((i, index) => {
      return {
        label: i.name,
        value: i.keyid,
        standsDays: monthDatas.filter((o) => o.fkuserid == i.keyid).length,
      };
    });
};

const dialogClose = () => {
  form.standbyDate = dayjs(new Date()).format("YYYY-MM-DD");
  userList.value = [];
  emits("close");
};

watch(
  () => attrs.open,
  async () => {
    if (attrs.open == true) {
      clickDateValue.value = dayjs(props.calenderValue || new Date()).format("YYYY-MM-DD");
      form.standbyDate = dayjs(props.calenderValue || new Date()).format("YYYY-MM-DD");
      await getCalendarData();
      if (attrs.keyid != "") {
        await getHX();
      } else {
        for (let key in form) {
          if (key != "standbyDate") {
            form[key] = "";
            form["fkuserids"] = "";
            form["keyid"] = "";
            form["backuptype"] = 1;
          }
        }
      }
    }
  }
);

watch(
  () => form.fkuserids,
  async () => {
    showUserList();
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.u-name-box {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  text-align: center;
  line-height: 80px;
  background: linear-gradient(348deg, #1890ff 0%, #dbedfe 100%);
  font-size: var(--font-size-level-1);
  color: #fff;
}

.u-span-name {
  font-weight: 400;
  font-size: var(--font-size-level-2);
  color: #1890ff;
}

.u-span-value {
  font-weight: 400;
  font-size: var(--font-size-level-1);
  color: #666666;
}
</style>
